package com.ssy.lingxi.product.serviceImpl.price;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.product.GoodsPriceStatusEnum;
import com.ssy.lingxi.common.constant.product.GoodsPriceTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.contract.api.feign.ContractControllerFeign;
import com.ssy.lingxi.contract.api.model.vo.request.ContrPriceQueryRequest;
import com.ssy.lingxi.contract.api.model.vo.response.ContractPriceQueryVO;
import com.ssy.lingxi.order.api.feign.OrderFeignService;
import com.ssy.lingxi.order.api.model.vo.request.OrderPriceQueryRequest;
import com.ssy.lingxi.order.api.model.vo.response.OrderPriceQueryVO;
import com.ssy.lingxi.product.api.model.request.price.*;
import com.ssy.lingxi.product.common.enums.MaterialsAddInternalStatusEnum;
import com.ssy.lingxi.product.entity.Brand;
import com.ssy.lingxi.product.entity.Goods;
import com.ssy.lingxi.product.entity.customer.CustomerCategory;
import com.ssy.lingxi.product.entity.price.GoodsPrice;
import com.ssy.lingxi.product.entity.price.GoodsPriceHistory;
import com.ssy.lingxi.product.repository.GoodsRepository;
import com.ssy.lingxi.product.repository.price.GoodsPriceHistoryRepository;
import com.ssy.lingxi.product.repository.price.GoodsPriceRepository;
import com.ssy.lingxi.product.service.price.IPriceManagementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 价格管理实现类
 *
 * @author lxc
 * @version 2.0.0
 * @date 2022/3/25
 */
@Slf4j
@Service
public class PriceManagementServiceImpl implements IPriceManagementService {

    @Resource
    private GoodsPriceRepository goodsPriceRepository;

    @Resource
    private GoodsPriceHistoryRepository historyRepository;

    @Resource
    private GoodsRepository goodsRepository;

    @Resource
    private IRedisStringUtils redisStringUtils;

    @Resource
    private ContractControllerFeign contractControllerFeign;

    @Resource
    private OrderFeignService orderFeignService;

    /**
     * 查询货品价格列表
     *
     * @param pageVO            分页实体
     * @param goodsQueryRequest 货品价格查询类
     */
    @Override
    public Page<GoodsPrice> getGoodsPriceList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsPriceQueryRequest goodsQueryRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<GoodsPrice> goodsList = goodsPriceRepository.findAll(getSpecification(goodsQueryRequest, sysUser), page);
        goodsList.stream().forEach(goodsPrice -> {
            Goods goods = goodsPrice.getGoods();
            String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goods.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
            if (StringUtils.isNotEmpty(unit)) {
                goods.setUnitName(unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0]);
            } else {
                goods.setUnitName("");
            }
        });
        return goodsList;
    }

    /**
     * 查询物料价格历史列表 - 查看单个物料历史价格详情
     *
     * @param sysUser      登录信息
     * @param pageVO       分页对象
     * @param queryRequest 查询对象
     */
    @Override
    public Wrapper<PageData<GoodsPriceHistory>> getGoodsPriceHistory(UserLoginCacheDTO sysUser, PageVO pageVO, PriceHistoryQueryRequest queryRequest) {
        GoodsPrice goodsPrice = goodsPriceRepository.findById(queryRequest.getGoodsPriceId()).orElse(null);
        if (Objects.isNull(goodsPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<GoodsPriceHistory> goodsPriceList = historyRepository.findByGoodsPrice(goodsPrice, page);
        if (goodsPriceList.getTotalElements() <= 0) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        goodsPriceList.forEach(goodsPriceHistory -> {
            if (goodsPriceHistory.getUnitId() != null) {
                String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goodsPriceHistory.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
                if (StringUtils.isNotEmpty(unit)) {
                    goodsPriceHistory.setUnitName(unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0]);
                } else goodsPriceHistory.setUnitName("");
            } else goodsPriceHistory.setUnitName("");
        });
        return Wrapper.success(new PageData<>(goodsPriceList.getTotalElements(), goodsPriceList.getContent()));
    }

    /**
     * 物料价格历史列表 - 新增市场价
     *
     * @param addRequest 价格信息
     */
    @Override
    public Wrapper<Void> AddGoodsPrice(PriceAddRequest addRequest) {
        GoodsPrice goodsPrice = goodsPriceRepository.findById(addRequest.getGoodsPriceId()).orElse(null);
        if (Objects.isNull(goodsPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Goods goods = goodsPrice.getGoods();
        //冻结的物料不能修改价格
        if (MaterialsAddInternalStatusEnum.FROZEN.getCode().equals(goods.getInteriorState())) {
            throw new BusinessException(ResponseCode.PRODUCT_PLATFORM_MATERIAL_FROZEN);
        }
        goodsPrice.setMarketPrice(addRequest.getMarketPrice());
        goodsPriceRepository.saveAndFlush(goodsPrice);
        return Wrapper.success();
    }


    /**
     * 物料新增、修改时，同步更新价格库
     * 更新物料价格信息
     *
     * @param updateRequest 价格信息
     */
    @Transactional
    @Override
    public void updateGoodsPrice(PriceUpdateRequest updateRequest) {
        Goods goods = goodsRepository.findById(updateRequest.getGoodsId()).orElse(null);
        if (Objects.isNull(goods)) {
            throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
        }
        GoodsPrice price = goodsPriceRepository.findByGoods(goods);
        GoodsPrice oldPrice = null;
        if (Objects.isNull(price)) {
            //新增物料价格数据
            price = new GoodsPrice();
            price.setGoods(goods);
            price.setCreateTime(System.currentTimeMillis());
        } else {
            oldPrice = price;
        }
        //如果当前价格库物料的合同、订单信息变更, 新价格替换旧价格, 旧价格存入价格历史
        //从合同服务中查询 外部状态为已完成签约的合同零
        Double zero = 0D;
        ContrPriceQueryRequest request = new ContrPriceQueryRequest();
        request.setGoodsId(goods.getId());
        request.setCode(goods.getCode());
        request.setMemberId(goods.getMemberId());
        request.setMemberRoleId(goods.getMemberRoleId());
        Wrapper<ContractPriceQueryVO> result = contractControllerFeign.goodsPriceByGoods(request);
        if (ResponseCode.SUCCESS.getCode() == result.getCode() && Objects.nonNull(result.getData())) {
            ContractPriceQueryVO data = result.getData();
            //判断新旧价格信息是否变动
            boolean flag = Objects.nonNull(oldPrice) && ((StringUtils.isNotBlank(oldPrice.getCode()) && !data.getContractNo().equals(oldPrice.getCode()))
                    || (data.getTotalAmount().compareTo(oldPrice.getOrderPrice()) != 0));
            if (Objects.isNull(oldPrice) || zero.compareTo(oldPrice.getOrderPrice()) == 0 || flag) {
                price.setOrderPrice(data.getTotalAmount());
                price.setEffectiveStartTime(data.getStartTime());
                price.setEffectiveEndTime(data.getEndTime());
                price.setUpperMemberId(data.getPartyBMemberId());
                price.setUpperMemberName(data.getPartyBName());
                price.setUpperMemberRoleId(data.getPartyBRoleId());
                price.setPriceType(GoodsPriceTypeEnum.CONTRACT_PRICE.getCode());
                price.setStatus(GoodsPriceStatusEnum.NORMAL.getCode());
                price.setCode(data.getContractNo());
            }
            if (flag) {
                //旧价格存入价格历史记录
                GoodsPriceHistory history = BeanUtil.copyProperties(oldPrice, GoodsPriceHistory.class);
                BeanUtil.copyProperties(goods, history);
                history.setGoodsPrice(oldPrice);
                history.setId(null);
                history.setCode(oldPrice.getCode());
                history.setGoodsCode(goods.getCode());
                Brand brand = goods.getBrand();
                history.setBrandName(Objects.nonNull(brand) ? brand.getName() : "");
                CustomerCategory category = goods.getCustomerCategory();
                history.setCategoryName(Objects.nonNull(category) ? category.getName() : "");
                history.setCreateTime(System.currentTimeMillis());
                history.setCreateTime(System.currentTimeMillis());
                historyRepository.saveAndFlush(history);
            }
        } else {
            //如果合同数据没有该物料 则从订单服务查询 订单类型为 采购询价合同、采购竞价合同、采购招标合同、请购单采购 的订单
            OrderPriceQueryRequest orderPriceQueryRequest = new OrderPriceQueryRequest();
            orderPriceQueryRequest.setGoodsId(goods.getId());
            orderPriceQueryRequest.setCode(goods.getCode());
            orderPriceQueryRequest.setMemberId(goods.getMemberId());
            orderPriceQueryRequest.setMemberRoleId(goods.getMemberRoleId());
            Wrapper<OrderPriceQueryVO> orderResult = orderFeignService.goodsPriceByGoods(orderPriceQueryRequest);
            if (ResponseCode.SUCCESS.getCode() == orderResult.getCode() && Objects.nonNull(orderResult.getData())) {
                OrderPriceQueryVO data = orderResult.getData();
                BigDecimal totalAmount = data.getTotalAmount();
                if (totalAmount != null) {
                    Double totalPrice = totalAmount.doubleValue();
                    //判断新旧价格信息是否变动
                    boolean flag = Objects.nonNull(oldPrice) && ((StringUtils.isNotBlank(oldPrice.getCode()) && !data.getContractNo().equals(oldPrice.getCode()))
                            || (totalPrice.compareTo(oldPrice.getOrderPrice()) != 0));
                    if (Objects.isNull(oldPrice) || zero.compareTo(oldPrice.getOrderPrice()) == 0 || flag) {
                        price.setOrderPrice(totalPrice);
                        price.setEffectiveStartTime(data.getStartTime() != null ? data.getStartTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() : null);
                        price.setEffectiveEndTime(data.getEndTime() != null ? data.getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() : null);
                        price.setUpperMemberId(data.getPartyBMemberId());
                        price.setUpperMemberName(data.getPartyBName());
                        price.setUpperMemberRoleId(data.getPartyBRoleId());
                        price.setPriceType(GoodsPriceTypeEnum.ORDER_PRICE.getCode());
                        price.setStatus(GoodsPriceStatusEnum.NORMAL.getCode());
                        price.setCode(data.getContractNo());
                    }
                    if (flag) {
                        //旧价格存入价格历史记录
                        GoodsPriceHistory history = BeanUtil.copyProperties(oldPrice, GoodsPriceHistory.class);
                        BeanUtil.copyProperties(goods, history);
                        history.setGoodsPrice(oldPrice);
                        history.setId(null);
                        history.setCode(oldPrice.getCode());
                        history.setGoodsCode(goods.getCode());
                        Brand brand = goods.getBrand();
                        history.setBrandName(Objects.nonNull(brand) ? brand.getName() : "");
                        CustomerCategory category = goods.getCustomerCategory();
                        history.setCategoryName(Objects.nonNull(category) ? category.getName() : "");
                        history.setCreateTime(System.currentTimeMillis());
                        history.setCreateTime(System.currentTimeMillis());
                        historyRepository.saveAndFlush(history);
                    }
                }
            }
        }

        goodsPriceRepository.saveAndFlush(price);

    }

    /**
     * 物料删除时，同步更新价格库
     * 更新物料价格信息
     *
     * @param deleteRequest 价格信息
     */
    @Transactional
    @Override
    public void deleteGoodsPrice(PriceDeleteRequest deleteRequest) {
        List<Goods> goods = goodsRepository.findAllById(deleteRequest.getGoodsIds());
        if (CollectionUtils.isEmpty(goods)) {
            throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
        }
        List<GoodsPrice> priceList = goodsPriceRepository.findByGoodsIn(goods);
        if (CollectionUtils.isEmpty(priceList)) {
            throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //删除物料所有历史价格
        List<GoodsPriceHistory> histories = new ArrayList<>();
        priceList.forEach(goodsPrice -> histories.addAll(goodsPrice.getPriceHistorys()));
        if (!CollectionUtils.isEmpty(histories)) {
            historyRepository.deleteAll(histories);
        }
        goodsPriceRepository.deleteAll(priceList);
    }

    /**
     * 合同物料信息同步更新
     *
     * @param request 合同物料价格信息
     */
    @Transactional
    @Override
    public Wrapper<Void> changeContractGoodsPrice(ContractPriceRequest request) {
        log.info("合同状态变更通知商品服务更新物料价格, 物料信息:{}", JSONUtil.toJsonStr(request));
        List<MaterielPriceRequest> materielPrices = request.getMaterielPrices();
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndCodeIn(request.getPartyAMemberId(), request.getPartyARoleId(), materielPrices.stream().map(MaterielPriceRequest::getCode).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.success();
        }
        List<GoodsPrice> goodsPrices = goodsPriceRepository.findByGoodsIn(goods);
        if (CollectionUtils.isEmpty(goodsPrices)) {
            return Wrapper.success();
        }
        List<GoodsPriceHistory> histories = new ArrayList<>();
        GoodsPrice oldPrice = new GoodsPrice();
        for (GoodsPrice goodsPrice : goodsPrices) {
            BeanUtil.copyProperties(goodsPrice, oldPrice);
            Goods good = goodsPrice.getGoods();
            //如果合同为作废, 则查询最近的合同价格或订单价格, 新价格替换旧价格, 旧价格存入价格历史
            if (GoodsPriceStatusEnum.ABANDONED.getCode().equals(request.getStatus())) {
                //从合同服务中查询 外部状态为已完成签约的合同零
                ContrPriceQueryRequest contrPriceQueryRequest = new ContrPriceQueryRequest();
                contrPriceQueryRequest.setGoodsId(good.getId());
                contrPriceQueryRequest.setCode(good.getCode());
                contrPriceQueryRequest.setMemberId(good.getMemberId());
                contrPriceQueryRequest.setMemberRoleId(good.getMemberRoleId());
                Wrapper<ContractPriceQueryVO> result = contractControllerFeign.goodsPriceByGoods(contrPriceQueryRequest);
                if (ResponseCode.SUCCESS.getCode() == result.getCode() && Objects.nonNull(result.getData())) {
                    ContractPriceQueryVO data = result.getData();
                    goodsPrice.setOrderPrice(data.getTotalAmount());
                    goodsPrice.setEffectiveStartTime(data.getStartTime());
                    goodsPrice.setEffectiveEndTime(data.getEndTime());
                    goodsPrice.setUpperMemberId(data.getPartyBMemberId());
                    goodsPrice.setUpperMemberName(data.getPartyBName());
                    goodsPrice.setUpperMemberRoleId(data.getPartyBRoleId());
                    goodsPrice.setPriceType(GoodsPriceTypeEnum.CONTRACT_PRICE.getCode());
                    goodsPrice.setStatus(GoodsPriceStatusEnum.ABANDONED.getCode());
                    goodsPrice.setCode(data.getContractNo());
                } else {
                    //如果合同数据没有该物料 则从订单服务查询 订单类型为 采购询价合同、采购竞价合同、采购招标合同、请购单采购 的订单
                    OrderPriceQueryRequest orderPriceQueryRequest = new OrderPriceQueryRequest();
                    orderPriceQueryRequest.setGoodsId(good.getId());
                    orderPriceQueryRequest.setCode(good.getCode());
                    orderPriceQueryRequest.setMemberId(good.getMemberId());
                    orderPriceQueryRequest.setMemberRoleId(good.getMemberRoleId());
                    Wrapper<OrderPriceQueryVO> orderResult = orderFeignService.goodsPriceByGoods(orderPriceQueryRequest);
                    if (ResponseCode.SUCCESS.getCode() == orderResult.getCode() && Objects.nonNull(orderResult.getData())) {
                        OrderPriceQueryVO data = orderResult.getData();
                        BigDecimal totalAmount = data.getTotalAmount();
                        if (totalAmount != null) {
                            goodsPrice.setOrderPrice(totalAmount.doubleValue());
                            goodsPrice.setEffectiveStartTime(data.getStartTime() != null ? data.getStartTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() : null);
                            goodsPrice.setEffectiveEndTime(data.getEndTime() != null ? data.getEndTime().toInstant(ZoneOffset.of("+8")).toEpochMilli() : null);
                            goodsPrice.setUpperMemberId(data.getPartyBMemberId());
                            goodsPrice.setUpperMemberName(data.getPartyBName());
                            goodsPrice.setUpperMemberRoleId(data.getPartyBRoleId());
                            goodsPrice.setPriceType(GoodsPriceTypeEnum.ORDER_PRICE.getCode());
                            goodsPrice.setStatus(GoodsPriceStatusEnum.ABANDONED.getCode());
                            goodsPrice.setCode(data.getContractNo());
                        }
                    } else {
                        //否则清空合同/订单价格信息
                        goodsPrice.setOrderPrice(0D);
                        goodsPrice.setEffectiveStartTime(null);
                        goodsPrice.setEffectiveEndTime(null);
                        goodsPrice.setUpperMemberId(null);
                        goodsPrice.setUpperMemberName(null);
                        goodsPrice.setUpperMemberRoleId(null);
                        goodsPrice.setPriceType(null);
                        goodsPrice.setStatus(GoodsPriceStatusEnum.ABANDONED.getCode());
                        goodsPrice.setCode(null);
                    }
                }
                //旧价格存入价格历史记录
                GoodsPriceHistory history = BeanUtil.copyProperties(oldPrice, GoodsPriceHistory.class);
                BeanUtil.copyProperties(good, history);
                history.setGoodsPrice(goodsPrice);
                history.setId(null);
                history.setCode(oldPrice.getCode());
                history.setGoodsCode(good.getCode());
                Brand brand = good.getBrand();
                history.setBrandName(Objects.nonNull(brand) ? brand.getName() : "");
                CustomerCategory category = good.getCustomerCategory();
                history.setCategoryName(Objects.nonNull(category) ? category.getName() : "");
                history.setCreateTime(System.currentTimeMillis());
                histories.add(history);
            } else {
                //判断原来的物料是否有合同价格
                if (StringUtils.isNotBlank(goodsPrice.getCode())) {
                    //旧价格存入价格历史记录
                    GoodsPriceHistory history = BeanUtil.copyProperties(oldPrice, GoodsPriceHistory.class);
                    BeanUtil.copyProperties(good, history);
                    history.setGoodsPrice(goodsPrice);
                    history.setId(null);
                    history.setCode(oldPrice.getCode());
                    history.setGoodsCode(good.getCode());
                    Brand brand = good.getBrand();
                    history.setBrandName(Objects.nonNull(brand) ? brand.getName() : "");
                    CustomerCategory category = good.getCustomerCategory();
                    history.setCategoryName(Objects.nonNull(category) ? category.getName() : "");
                    history.setCreateTime(System.currentTimeMillis());
                    histories.add(history);
                }
                BeanUtil.copyProperties(request, goodsPrice);
                MaterielPriceRequest priceRequest = materielPrices.stream().filter(materielPrice -> materielPrice.getCode().equals(goodsPrice.getGoods().getCode())).findFirst().orElse(null);
                if (Objects.nonNull(priceRequest)) {
                    goodsPrice.setOrderPrice(priceRequest.getAmount());
                }
                goodsPrice.setUpperMemberId(request.getPartyBMemberId());
                goodsPrice.setUpperMemberName(request.getPartyBName());
                goodsPrice.setUpperMemberRoleId(request.getPartyBRoleId());
                goodsPrice.setEffectiveStartTime(request.getStartTime());
                goodsPrice.setEffectiveEndTime(request.getEndTime());
                goodsPrice.setCode(request.getContractNo());
                goodsPrice.setUpdateTime(System.currentTimeMillis());
                goodsPrice.setPriceType(GoodsPriceTypeEnum.CONTRACT_PRICE.getCode());
                goodsPrice.setStatus(GoodsPriceStatusEnum.NORMAL.getCode());
            }

        }
        goodsPriceRepository.saveAll(goodsPrices);
        goodsPriceRepository.flush();
        historyRepository.saveAll(histories);
        historyRepository.flush();
        return Wrapper.success();
    }

    /**
     * 订单物料信息同步更新
     *
     * @param request 物料价格信息
     */
    @Transactional
    @Override
    public Wrapper<Void> changeOrderGoodsPrice(OrderPriceRequest request) {
        log.info("订单确认收货通知商品服务更新物料价格, 物料信息:{}", JSONUtil.toJsonStr(request));
        List<MaterielPriceRequest> materielPrices = request.getMaterielPrices();
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndCodeIn(request.getPartyAMemberId(), request.getPartyARoleId(), materielPrices.stream().map(MaterielPriceRequest::getCode).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.success();
        }
        List<GoodsPrice> goodsPrices = goodsPriceRepository.findByGoodsIn(goods);
        if (CollectionUtils.isEmpty(goodsPrices)) {
            return Wrapper.success();
        }
        List<GoodsPriceHistory> histories = new ArrayList<>();
        GoodsPrice oldPrice = new GoodsPrice();
        for (GoodsPrice goodsPrice : goodsPrices) {
            BeanUtil.copyProperties(goodsPrice, oldPrice);
            Goods good = oldPrice.getGoods();
            //1. 判断原来的物料是是否有价格
            //1.1 有价格则判断是合同还是订单价格
            if (StringUtils.isNotBlank(goodsPrice.getCode())) {
                //1.1.1 合同价格不做操作
                if (GoodsPriceTypeEnum.CONTRACT_PRICE.getCode().equals(goodsPrice.getPriceType())){
                    continue;
                }
                //1.1.2 订单价格,则覆盖旧数据, 旧数据存入历史价格库
                BeanUtil.copyProperties(request, goodsPrice);
                MaterielPriceRequest priceRequest = materielPrices.stream().filter(materielPrice -> materielPrice.getCode().equals(goodsPrice.getGoods().getCode())).findFirst().orElse(null);
                if (Objects.nonNull(priceRequest)) {
                    goodsPrice.setOrderPrice(priceRequest.getAmount());
                }
                goodsPrice.setUpperMemberId(request.getPartyBMemberId());
                goodsPrice.setUpperMemberName(request.getPartyBName());
                goodsPrice.setUpperMemberRoleId(request.getPartyBRoleId());
                goodsPrice.setEffectiveStartTime(request.getStartTime());
                goodsPrice.setEffectiveEndTime(request.getEndTime());
                goodsPrice.setCode(request.getContractNo());
                goodsPrice.setUpdateTime(System.currentTimeMillis());
                goodsPrice.setPriceType(GoodsPriceTypeEnum.ORDER_PRICE.getCode());
                goodsPrice.setStatus(GoodsPriceStatusEnum.CHANGE.getCode());
                //旧价格存入价格历史记录
                GoodsPriceHistory history = BeanUtil.copyProperties(oldPrice, GoodsPriceHistory.class);
                BeanUtil.copyProperties(good, history);
                history.setGoodsPrice(goodsPrice);
                history.setId(null);
                history.setCode(oldPrice.getCode());
                history.setGoodsCode(good.getCode());
                Brand brand = good.getBrand();
                history.setBrandName(Objects.nonNull(brand) ? brand.getName() : "");
                CustomerCategory category = good.getCustomerCategory();
                history.setCategoryName(Objects.nonNull(category) ? category.getName() : "");
                history.setCreateTime(System.currentTimeMillis());
                histories.add(history);
            }else {
                //1.2 无价格,则填充该物料价格信息
                BeanUtil.copyProperties(request, goodsPrice);
                MaterielPriceRequest priceRequest = materielPrices.stream().filter(materielPrice -> materielPrice.getCode().equals(goodsPrice.getGoods().getCode())).findFirst().orElse(null);
                if (Objects.nonNull(priceRequest)) {
                    goodsPrice.setOrderPrice(priceRequest.getAmount());
                }
                goodsPrice.setUpperMemberId(request.getPartyBMemberId());
                goodsPrice.setUpperMemberName(request.getPartyBName());
                goodsPrice.setUpperMemberRoleId(request.getPartyBRoleId());
                goodsPrice.setEffectiveStartTime(request.getStartTime());
                goodsPrice.setEffectiveEndTime(request.getEndTime());
                goodsPrice.setCode(request.getContractNo());
                goodsPrice.setUpdateTime(System.currentTimeMillis());
                goodsPrice.setPriceType(GoodsPriceTypeEnum.ORDER_PRICE.getCode());
                goodsPrice.setStatus(GoodsPriceStatusEnum.CHANGE.getCode());
            }
        }
        goodsPriceRepository.saveAll(goodsPrices);
        goodsPriceRepository.flush();
        historyRepository.saveAll(histories);
        historyRepository.flush();
        return Wrapper.success();
    }


    /**
     * 构建查询条件
     */
    private Specification<GoodsPrice> getSpecification(GoodsPriceQueryRequest goodsQueryRequest, UserLoginCacheDTO sysUser) {
        return (Specification<GoodsPrice>) (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();

            //价格实体类
            Join<Object, Object> goodsJoin = root.join("goods");
            if (!StringUtils.isEmpty(goodsQueryRequest.getName())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(goodsJoin.get("name").as(String.class), "%" + goodsQueryRequest.getName() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryRequest.getCode())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(goodsJoin.get("code").as(String.class), "%" + goodsQueryRequest.getCode() + "%"));
            }
            if (goodsQueryRequest.getBrandId() != null && goodsQueryRequest.getBrandId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(goodsJoin.get("brand").as(Brand.class), goodsQueryRequest.getBrandId()));
            }
            if (StringUtils.isNotBlank(goodsQueryRequest.getUppreMemberName())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("upperMemberName").as(String.class), "%" + goodsQueryRequest.getUppreMemberName() + "%"));
            }
            if (StringUtils.isNotBlank(goodsQueryRequest.getCustomerCategoryId())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(goodsJoin.get("customerCategory").get("name").as(String.class), "%" + goodsQueryRequest.getCustomerCategoryId() + "%"));
            }
            //展示当前登录会员的物料信息
            finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(goodsJoin.get("memberId").as(Long.class), sysUser.getMemberId()));
            finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(goodsJoin.get("memberRoleId").as(Long.class), sysUser.getMemberRoleId()));
            query.orderBy(criteriaBuilder.asc(goodsJoin.get("code")));
            return finalConditions;
        };
    }

}

